<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="秒杀状态">
        <el-select 
          v-model="queryParams.state" 
          placeholder="请选择秒杀状态" 
          clearable 
          @keyup.enter="handleQuery" 
          style="width: 200px">
          <el-option label="未开始" value="1" />
          <el-option label="进行中" value="2" />
          <el-option label="已结束" value="3" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="活动时间">
          <div class="block" style="margin-right: 10px; display: inline-block;">
            <el-date-picker
              v-model="queryForm.activityTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['user:sku:add']"
        >新增秒杀</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['user:sku:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="skuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
      <el-table-column label="活动时间" align="center" prop="activityTime" width="287x"/>
      <el-table-column label="秒杀库存" align="center" prop="seckillStock" />
      <el-table-column label="秒杀状态">
        <template #default="scope">
          <el-tag v-if="scope.row.state === 1" type="info">未开始</el-tag>
          <el-tag v-if="scope.row.state === 2" type="success">进行中</el-tag>
          <el-tag v-if="scope.row.state === 3" type="danger">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['user:sku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['user:sku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加秒杀活动对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="seckillRef" :model="form" :rules="rules" label-width="100px">
        <el-collapse v-model="activeTab">
          <el-collapse-item title="基本信息" name="basic">
            <el-form-item label="秒杀名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入秒杀名称" />
            </el-form-item>
            <el-form-item label="活动时间" prop="activityTime">
              <el-date-picker
                v-model="form.activityTime"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="商品设置" name="product">
            <el-form-item>
              <el-button type="primary" @click="openProductSelectDialog">选择商品</el-button>
              <el-table v-if="selectedProducts.length > 0" :data="selectedProducts" style="margin-top: 10px">
                <el-table-column prop="productName" label="商品名称" width="180" />
                <el-table-column prop="sellingPrice" label="售价(元)" width="100" />
                <el-table-column prop="seckillPrice" label="秒杀价(元)" width="100">
                  <template #default="scope">
                    <el-input v-model="scope.row.seckillPrice" placeholder="请输入" size="small" />
                  </template>
                </el-table-column>
                <el-table-column prop="seckillStock" label="秒杀库存" width="100">
                  <template #default="scope">
                    <el-input v-model="scope.row.seckillStock" placeholder="请输入" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button type="danger" icon="Delete" size="small" @click="removeProduct(scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择商品对话框 -->
    <el-dialog title="选择商品" v-model="productSelectOpen" width="800px" append-to-body>
      <el-form :model="productQuery" ref="productQueryRef" :inline="true" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="productQuery.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchProducts">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="productList" @selection-change="handleProductSelectionChange" style="margin-top: 10px">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productName" label="商品名称" width="200" />
        <el-table-column prop="productPrice" label="售价(元)" width="100" />
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="salesVolume" label="销量" width="100" />
      </el-table>
      <pagination
        v-show="productTotal > 0"
        :total="productTotal"
        v-model:page="productQuery.pageNum"
        v-model:limit="productQuery.pageSize"
        @pagination="searchProducts"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmProductSelection">确 定</el-button>
          <el-button @click="productSelectOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Sku">
import { listSku, getSku, addSku, updateSku } from "@/api/seckill/seckill"
import { listProductPage } from "@/api/product/product"
import { ref, reactive, toRefs, onMounted } from "vue"

const { proxy } = getCurrentInstance()

// 商品选择相关变量
const productSelectOpen = ref(false)
const productList = ref([])
const productTotal = ref(0)
const selectedProducts = ref([])
const selectedProductRows = ref([])

const skuList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    state: null,
    activityName: null
  },
  productQuery: {
      categoryId: '',
      productName: '',
      status: 'all',
      pageNum: 1,
      pageSize: 10
    },
  rules: {
    activityName: [
      { required: true, message: "秒杀名称不能为空", trigger: "blur" }
    ],
    activityTime: [
      { required: true, message: "活动时间不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询秒杀商品SKU列表 */
  function getList() {
    loading.value = true
    listSku(queryParams.value).then(response => {
      skuList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 初始化商品查询参数
  onMounted(() => {
    data.productQuery = {
      categoryId: '',
      productName: '',
      // status: 'all',
      pageNum: 1,
      pageSize: 10
    }
  })

  // 打开商品选择对话框
  function openProductSelectDialog() {
    productSelectOpen.value = true
    searchProducts()
  }

// 搜索商品
function searchProducts() {
  loading.value = true
  listProductPage(data.productQuery).then(response => {
    productList.value = response.rows
    productTotal.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('获取商品列表失败:', error)
    loading.value = false
  })
}

// 处理商品选择变化
function handleProductSelectionChange(selection) {
  selectedProductRows.value = selection
}

// 确认商品选择
function confirmProductSelection() {
  if (selectedProductRows.value && selectedProductRows.value.length > 0) {
    const selected = selectedProductRows.value.map(item => ({
      ...item,
      seckillPrice: '',
      seckillStock: ''
    }))
    // 避免重复添加
    selected.forEach(newItem => {
      const exists = selectedProducts.value.some(item => item.id === newItem.id)
      if (!exists) {
        selectedProducts.value.push(newItem)
      }
    })
  }
  productSelectOpen.value = false
}

// 移除已选择的商品
function removeProduct(row) {
  selectedProducts.value = selectedProducts.value.filter(item => item.id !== row.id)
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityName: null,
    activityTime: null,
    remark: null
  }
  selectedProducts.value = []
  proxy.resetForm("seckillRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加秒杀商品SKU"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSku(_id).then(response => {
    form.value = response.data
    // 模拟加载已选择的商品
    selectedProducts.value = [{
      id: 1, productName: '示例商品', sellingPrice: 100.00,
      seckillPrice: form.value.seckillPrice,
      seckillStock: form.value.seckillStock
    }]
    open.value = true
    title.value = "修改秒杀活动"
  })
}

/** 提交按钮 */
function submitForm() {
  if (form.value.id != null) {
    updateSku(submitData).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      open.value = false
      getList()
    })
  } else {
    addSku(submitData).then(response => {
      proxy.$modal.msgSuccess("新增成功")
      open.value = false
      getList()
    })
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('seckill/seckill/export', {
    ...queryParams.value
  }, `sku_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.empty-tip {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.el-collapse-item__header {
  font-weight: bold;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px;
}

/* 调整商品选择对话框中表格的样式 */
.el-dialog__body .el-table {
  margin-top: 15px;
}

/* 调整标签页样式 */
.el-tabs {
  margin-top: 15px;
}
</style>
